package org.example;

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.util.*;
import java.util.List;
import javax.swing.border.*;

public class StudentManagementFrame extends JFrame {
    private JTable studentTable;
    private DefaultTableModel tableModel;
    private JTextField idField, nameField, ageField, classField;
    private JComboBox<String> genderBox;
    private List<Student> students;
    private JTextField searchField;

    public StudentManagementFrame() {
        setTitle("学生管理系统");
        setSize(1000, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 加载已保存的学生数据
        students = FileUtil.loadStudents();

        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));

        // 创建搜索面板
        createSearchPanel(mainPanel);

        // 创建左侧面板（输入区域）
        createLeftPanel(mainPanel);

        // 创建右侧面板（表格）
        createRightPanel(mainPanel);

        add(mainPanel);

        // 加载现有数据到表格
        loadStudentsToTable();

        // 添加窗口关闭事件
        addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing(java.awt.event.WindowEvent windowEvent) {
                FileUtil.saveStudents(students);
            }
        });
    }

    private void createSearchPanel(JPanel mainPanel) {
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        searchField = new JTextField(20);
        JButton searchButton = new JButton("搜索");

        searchPanel.add(new JLabel("搜索："));
        searchPanel.add(searchField);
        searchPanel.add(searchButton);

        searchButton.addActionListener(e -> searchStudents());

        mainPanel.add(searchPanel, BorderLayout.NORTH);
    }

    private void createLeftPanel(JPanel mainPanel) {
        JPanel leftPanel = new JPanel();
        leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
        leftPanel.setBorder(BorderFactory.createTitledBorder("学生信息输入"));

        // 创建输入字段
        JPanel inputPanel = new JPanel(new GridLayout(5, 2, 5, 10));
        inputPanel.setBorder(new EmptyBorder(10, 10, 10, 10));

        inputPanel.add(new JLabel("学号:"));
        idField = new JTextField();
        inputPanel.add(idField);

        inputPanel.add(new JLabel("姓名:"));
        nameField = new JTextField();
        inputPanel.add(nameField);

        inputPanel.add(new JLabel("性别:"));
        genderBox = new JComboBox<>(new String[]{"男", "女"});
        inputPanel.add(genderBox);

        inputPanel.add(new JLabel("年龄:"));
        ageField = new JTextField();
        inputPanel.add(ageField);

        inputPanel.add(new JLabel("班级:"));
        classField = new JTextField();
        inputPanel.add(classField);

        leftPanel.add(inputPanel);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout());

        JButton addButton = createStyledButton("添加", new Color(46, 204, 113));
        JButton updateButton = createStyledButton("修改", new Color(52, 152, 219));
        JButton deleteButton = createStyledButton("删除", new Color(231, 76, 60));
        JButton clearButton = createStyledButton("清空", new Color(149, 165, 166));

        buttonPanel.add(addButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(clearButton);

        leftPanel.add(buttonPanel);

        addButton.addActionListener(e -> addStudent());
        updateButton.addActionListener(e -> updateStudent());
        deleteButton.addActionListener(e -> deleteStudent());
        clearButton.addActionListener(e -> clearFields());

        mainPanel.add(leftPanel, BorderLayout.WEST);
    }

    private void createRightPanel(JPanel mainPanel) {
        JPanel rightPanel = new JPanel(new BorderLayout());
        rightPanel.setBorder(BorderFactory.createTitledBorder("学生列表"));

        String[] columnNames = {"学号", "姓名", "性别", "年龄", "班级"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        studentTable = new JTable(tableModel);
        studentTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        studentTable.setRowHeight(25);
        studentTable.getTableHeader().setReorderingAllowed(false);

        // 设置表格列宽
        studentTable.getColumnModel().getColumn(0).setPreferredWidth(100);
        studentTable.getColumnModel().getColumn(1).setPreferredWidth(100);
        studentTable.getColumnModel().getColumn(2).setPreferredWidth(50);
        studentTable.getColumnModel().getColumn(3).setPreferredWidth(50);
        studentTable.getColumnModel().getColumn(4).setPreferredWidth(150);

        JScrollPane scrollPane = new JScrollPane(studentTable);
        rightPanel.add(scrollPane, BorderLayout.CENTER);

        studentTable.getSelectionModel().addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                int row = studentTable.getSelectedRow();
                if (row != -1) {
                    Student student = students.get(row);
                    displayStudent(student);
                }
            }
        });

        mainPanel.add(rightPanel, BorderLayout.CENTER);
    }

    private JButton createStyledButton(String text, Color color) {
        JButton button = new JButton(text);
        button.setPreferredSize(new Dimension(80, 30));
        button.setBackground(color);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorderPainted(false);

        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(color.brighter());
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(color);
            }
        });

        return button;
    }

    private void searchStudents() {
        String searchText = searchField.getText().toLowerCase().trim();
        tableModel.setRowCount(0);

        for (Student student : students) {
            if (student.getId().toLowerCase().contains(searchText) ||
                student.getName().toLowerCase().contains(searchText) ||
                student.getClassName().toLowerCase().contains(searchText)) {
                addStudentToTable(student);
            }
        }
    }

    private void loadStudentsToTable() {
        tableModel.setRowCount(0);
        for (Student student : students) {
            addStudentToTable(student);
        }
    }

    private void addStudentToTable(Student student) {
        tableModel.addRow(new Object[]{
            student.getId(),
            student.getName(),
            student.getGender(),
            student.getAge(),
            student.getClassName()
        });
    }

    private void displayStudent(Student student) {
        idField.setText(student.getId());
        nameField.setText(student.getName());
        genderBox.setSelectedItem(student.getGender());
        ageField.setText(String.valueOf(student.getAge()));
        classField.setText(student.getClassName());
    }

    private void addStudent() {
        try {
            validateInput();

            Student student = new Student(
                idField.getText().trim(),
                nameField.getText().trim(),
                genderBox.getSelectedItem().toString(),
                Integer.parseInt(ageField.getText().trim()),
                classField.getText().trim()
            );

            students.add(student);
            addStudentToTable(student);
            clearFields();
            FileUtil.saveStudents(students);

            JOptionPane.showMessageDialog(this, "添加成功！");
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void updateStudent() {
        int selectedRow = studentTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要修改的学生！");
            return;
        }

        try {
            validateInput();

            Student student = students.get(selectedRow);
            student.setId(idField.getText().trim());
            student.setName(nameField.getText().trim());
            student.setGender(genderBox.getSelectedItem().toString());
            student.setAge(Integer.parseInt(ageField.getText().trim()));
            student.setClassName(classField.getText().trim());

            loadStudentsToTable();
            clearFields();
            FileUtil.saveStudents(students);

            JOptionPane.showMessageDialog(this, "修改成功！");
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void deleteStudent() {
        int selectedRow = studentTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要删除的学生！");
            return;
        }

        int result = JOptionPane.showConfirmDialog(this,
            "确定要删除这条记录吗？", "确认",
            JOptionPane.YES_NO_OPTION);

        if (result == JOptionPane.YES_OPTION) {
            students.remove(selectedRow);
            tableModel.removeRow(selectedRow);
            clearFields();
            FileUtil.saveStudents(students);
        }
    }

    private void validateInput() throws Exception {
        if (idField.getText().trim().isEmpty()) {
            throw new Exception("学号不能为空！");
        }
        if (nameField.getText().trim().isEmpty()) {
            throw new Exception("姓名不能为空！");
        }
        try {
            int age = Integer.parseInt(ageField.getText().trim());
            if (age <= 0 || age > 150) {
                throw new Exception("请输入有效的年龄！");
            }
        } catch (NumberFormatException e) {
            throw new Exception("年龄必须是数字！");
        }
        if (classField.getText().trim().isEmpty()) {
            throw new Exception("班级不能为空！");
        }
    }

    private void clearFields() {
        idField.setText("");
        nameField.setText("");
        genderBox.setSelectedIndex(0);
        ageField.setText("");
        classField.setText("");
        studentTable.clearSelection();
    }
}
